package com.example.design.ddd.practice2.application.payment;

import cn.hutool.core.lang.ObjectId;
import com.example.design.ddd.practice2.domain.Payment.entity.Payment;
import com.example.design.ddd.practice2.domain.Payment.PaymentStatus;
import com.example.design.ddd.practice2.domain.Payment.repository.PaymentGateway;
import com.example.design.ddd.practice2.domain.Payment.valueobject.PaymentRequest;
import com.example.design.ddd.practice2.domain.Payment.valueobject.PaymentResult;
import com.example.design.ddd.practice2.domain.order.entity.Order;
import com.example.design.ddd.practice2.domain.order.entity.OrderItem;
import com.example.design.ddd.practice2.domain.order.valueobject.Money;

import java.time.LocalDateTime;
import java.util.List;

// 支付应用服务实现
public class PaymentService {
    private final PaymentGateway paymentGateway; // 支付网关接口

    public PaymentService(PaymentGateway paymentGateway) {
        this.paymentGateway = paymentGateway;
    }

    public Payment createPayment(Order order, PaymentRequest request) {
        // 验证订单金额
        Money totalAmount = calculateTotal(order.getItems());
        if (!totalAmount.equals(request.getAmount())) {
            throw new RuntimeException("支付金额不匹配");
        }
        
        // 调用支付网关
        PaymentResult result = paymentGateway.process(request);
        
        // 创建支付记录
        Payment payment = new Payment();
        payment.setPaymentId(ObjectId.next());
        payment.setOrderId(order.getOrderId());
        payment.setAmount(request.getAmount());
        payment.setStatus(result.isSuccess() ? 
            PaymentStatus.SUCCESS : PaymentStatus.FAILED);
        payment.setPaidTime(LocalDateTime.now());
        
        return payment;
    }
    
    private Money calculateTotal(List<OrderItem> items) {
        return items.stream()
            .map(OrderItem::total)
            .reduce(Money::add)
            .orElseThrow(() -> new RuntimeException("订单金额计算失败"));
    }
}